import axios from 'axios'
import { Message } from 'element-ui';
import store from '../store'
import router from '../router/index'
import { gettimeout } from '.././utils/auth'
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
const time = 60 * 60 * 1000

instance.interceptors.response.use((response) => {

  const { data, message, success } = response.data
  if (success) {
    return data
  } else {
    Message({
      type: 'error',
      message: message
    })
    return Promise.reject(new Error(message))
  }
}, (error) => {
  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/remoto')
    Message({
      type: 'error',
      message: '登录状态过期，请重新登录'
    })
    router.push('/login')
  } else {
    Message.error(error.message)
  }
  // 对响应错误做点什么
  return Promise.reject(error);
})


// function checkTime() {
//   var currentTime = Date.now()
//   var tokenTime = getTimeStamp()
//   var space = currentTime - tokenTime
//   return space > tiem
// }

instance.interceptors.request.use(
  config => {
    // 获取 token
    // const token = getToken()
    const token = store.getters.token
    if (token) {
      // 统一设置请求头中的 token
      const ischecktime = Date.now() - gettimeout()
      if (ischecktime > time) {
        store.dispatch('user/remoto')
        router.push('/login')
        return Promise.reject(new Error('token 超时'))
      }
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)




export default instance